<?php
namespace app\index\controller;
use think\Db;
use think\Request;
use think\Controller;
use think\Validate;
use think\Exception;
use excel\Excels as excels;

class Manage extends Base
{
    public $manage;
    public function __construct()
    {
        parent::__construct();
        $this->manage = model('CrmManage');
    }

    // 管理员角色列表
    public function manageJueseList()
    {
        $data = input();//token type
        if (empty($data['type'])) {
            apiReturn(201,'角色类型不能为空');
        }
        $list = $this->manage->jueseList($data['type']);
        apiReturn(200,'获取列表成功',$list);
    }

    // 新增员工接口
    public function manageAdd()
    {
        $data = input();//token username name password chkpass group_id zu_id zu_watch jiaowus教务工号(1000,1001) allow_ip allow_mac phone pic is_xiaoshou status

        $validate = new \app\index\validate\CrmManage;
        $scene = empty($data['password']) ? 'edit' : 'add';
        if ($validate->scene($scene)->check($data)) {
            $data['fenzu_name'] = db('crm_fenzu')->where('id',$data['zu_id'])->value('name');
            unset($data['token']);
            if (empty($data['password'])) {
                $data['password'] = password('123456');
            }
            $this->manage->save($data);
            apiReturn(200,'新增工号成功');
        }else{
            apiReturn(201,$validate->getError());
        }
    }

    // 员工列表接口
    public function manageList()
    {
        $data = input();//token group_id zu_id username name rows page

        $where = [];
        $manage_author = $this->getManageAuthor();
        if ($manage_author['is_xiaoshou'] == 1) {
            $where['username'] = $this->getManageList();
        }
        if (isset($data['group_id'])) {
            if (!empty($data['group_id'])) {
                $where['group_id'] = $data['group_id'];
            }
        }
        if (isset($data['zu_id'])) {
            if (!empty($data['zu_id'])) {
                $wherezu_id = $this->getFenzuList($data['zu_id']);
                $where['username'] = $this->getManageList($wherezu_id);
            }
        }
        if (isset($data['username'])) {
            if (!empty($data['username'])) {
                $where['username'] = array('like','%'.$data['username'].'%');
            }
        }
        if (isset($data['name'])) {
            if (!empty($data['name'])) {
                $where['name'] = array('like','%'.$data['name'].'%');
            }
        }
        if (isset($data['status'])) {
            if ($data['status'] != '') {
                $where['status'] = $data['status'];
            }
        }
        
        $manageList = db('crm_manage')->where($where)->limit(($data['page']-1)*$data['rows'],$data['rows'])->order('status DESC,zu_id ASC,date DESC')->select();
        $count = db('crm_manage')->where($where)->count();
        foreach ($manageList as $key => $value) {
            $manageList[$key]['group_id'] = db('crm_group')->where('id',$value['group_id'])->value('name');
            // $manageList[$key]['status'] = ''.$value['status'].'';
        }

        $datas = array(
            'manageList'=>$manageList,
            'count'=>$count
        );
        apiReturn(200,'获取员工列表成功',$datas);
    }

    // 后端人员列表
    public function houduanList()
    {
        $data = input();//token
        $list = db('crm_manage')->field('username,name')->where(['type'=>2,'status'=>1])->select();
        apiReturn(200,'获取后端人员列表成功',$list);
    }

    //班主任列表
    public function banzhurenList()
    {
        $data = input();//token
        $list = db('crm_manage')->field('username,name')->where(['type'=>3,'status'=>1])->select();
        apiReturn(200,'获取班主任列表成功',$list);
    }

    //邀约对应教务列表
    public function jiaowuList()
    {
        $data = input();//token
        $manage_author = $this->getManageAuthor();
        $list = [];
        if ($manage_author['manage_type'] == 1) {
            $jiaowus = db('crm_manage')->where('username',$manage_author['username'])->value('jiaowus');
            if (!empty($jiaowus)) {
                $list = db('crm_manage')->field('username,name')->where(['username'=>['in',$jiaowus]])->select();
            }
        }
        apiReturn(200,'获取教务列表成功',$list);
    }

    // 获取工号信息接口
    public function manageInfo()
    {
        $data = input();//token id

        if (empty($data['id'])) {
            $manageInfo = $this->manage->getManageInfo($data['token']);
        }else{
            $manageInfo = $this->manage->getManageInfo('','',$data['id']);
        }
        $group1=[];
        $group2=[];
        if(isset($manageInfo['id'])){
            $group1 = db('crm_group_author')->where(['group_id'=>$manageInfo['group_id'],'type'=>1])->column('author');
            $group2 = db('crm_group_author')->where(['group_id'=>$manageInfo['group_id'],'type'=>2])->column('author');
        }
        $manageInfo['group1']=$group1;
        $manageInfo['group2']=$group2;
        if (!empty($manageInfo['jiaowus'])) {
            $manageInfo['jiaowus'] = explode(',', $manageInfo['jiaowus']);
        }
        if (!empty($manageInfo['banzhuren_grade'])) {
            $manageInfo['banzhuren_grade'] = explode(',', $manageInfo['banzhuren_grade']);
        }else{
            $manageInfo['banzhuren_grade'] = [];
        }
        if (!empty($manageInfo['zu_watch'])) {
            $zu_watch = explode(',', $manageInfo['zu_watch']);
            foreach ($zu_watch as &$value){
                $value=(int)$value;
            }
            $manageInfo['zu_watch'] = $zu_watch;

            // $zu_watch = [];
            // foreach ($manageInfo['zu_watch'] as $key => $value) {
            //     $zu_name = db('crm_fenzu')->where('id',$value)->value('name');
            //     $zu_watch[] = ['id'=>$value,'name'=>$zu_name];
            // }
            // $manageInfo['zu_watch'] = $zu_watch;
        }
        $manage_author = $this->getManageAuthor();
        $manageInfo['group_name'] = $manage_author['group_name'];
        
        apiReturn(200,'获取工号信息成功',$manageInfo);
    }

    // 修改员工接口
    public function manageEdit()
    {
        $data = input();//token id username name password chkpass group_id zu_id zu_watch jiaowus教务工号(1000,1001) allow_ip allow_mac phone is_xiaoshou status

        $validate = new \app\index\validate\CrmManage;
        $scene = empty($data['password']) ? 'edit' : 'add';
        if ($validate->scene($scene)->check($data)) {
            $data['fenzu_name'] = db('crm_fenzu')->where('id',$data['zu_id'])->value('name');
            unset($data['token']);
            if (empty($data['password'])) {
                unset($data['password']);
            }
            $oldusername = $this->manage->where('id',$data['id'])->value('username');
            $this->manage->save($data,['id'=>$data['id']]);

            //修改工号时修改客户归属和订单归属
            // db('crm_customer')->where(array('manage_id'=>$oldusername))->update(['manage_id'=>$data['username']]);
            // db('crm_order')->where(array('manage_id'=>$oldusername))->update(['manage_id'=>$data['username'],'zu_id'=>$data['zu_id'],'zu_name'=>$data['fenzu_name']]);
            // db('crm_order_money')->where(array('manage_id'=>$oldusername))->update(['manage_id'=>$data['username'],'zu_id'=>$data['zu_id'],'fenzu_name'=>$data['fenzu_name']]);

            apiReturn(200,'修改工号成功');
        }else{
            apiReturn(201,$validate->getError());
        }
    }

    public function runrun()
    {
        $list = db('crm_manage')->select();
        foreach ($list as $key => $value) {
            db('crm_order')->where(array('manage_id'=>$value['username']))->update(['manage_id'=>$value['username'],'zu_id'=>$value['zu_id'],'zu_name'=>$value['fenzu_name']]);
            db('crm_order_money')->where(array('manage_id'=>$value['username']))->update(['manage_id'=>$value['username'],'zu_id'=>$value['zu_id'],'fenzu_name'=>$value['fenzu_name']]);
        }
        echo "运行成功";
    }

    // 删除工号接口
    public function manageDelete()
    {
        $data = input();//token id
        if (empty($data['id'])) {
            apiReturn(201,'管理员id不能为空');
        }
        $manage = db('crm_manage')->field('username,name')->where('id',$data['id'])->find();
        db('crm_manage')->where('id',$data['id'])->delete();

        $manage_author = $this->getManageAuthor();
        $this->operationAdd($manage_author['username'], '删除工号', $manage['username'], $manage['name']);

        apiReturn(200,'删除工号成功');
    }

    // 修改工号状态
    public function manageStatus()
    {
        $data = input();//token id

        $status = db('crm_manage')->where('id',$data['id'])->value('status');
        if ($status == 1) {
            $datas['status'] = 0;
        }else{
            $datas['status'] = 1;
        }
        db('crm_manage')->where('id',$data['id'])->update($datas);
        apiReturn(200,'修改成功');
    }

    // 修改密码
    public function setPassword()
    {
        $data = input();//token username password newpass chkpass

        $validate = new Validate(
            [
                'username'=>'require',
                'password'=>'require',
                'newpass'=>'require|length:6,12|confirm:chkpass'
            ],
            [
                'username.require'=>'用户名不能为空',
                'password.require'=>'原密码不能为空',
                'newpass.require'=>'新密码不能为空',
                'newpass.length'=>'新密码长度须在6-12位',
                'newpass.confirm'=>'新密码不一致'
            ]
        );
        if ($validate->check($data)) {
            $oneManage = db('crm_manage')->field('id,password')->where(array('username'=>$data['username'],'token'=>$data['token']))->find();
            if (!empty($oneManage)) {
                if ($oneManage['password'] == password($data['password'])) {
                    db('crm_manage')->where('id',$oneManage['id'])->update(['password'=>password($data['newpass'])]);
                    apiReturn(200,'修改密码成功');
                }else{
                    apiReturn(201,'用户名或原密码错误');
                }
            }else{
                apiReturn(202,'用户名或原密码错误');
            }
        }else{
            apiReturn(203,$validate->getError());
        }
    }

    // 登录日志
    public function loginLogList()
    {
        $data = input();//token rows page

        $where = [];
        if (isset($data['manage_id'])) {
            if (!empty($data['manage_id'])) {
                $where['username'] = $data['manage_id'];
            }
        }
        if (isset($data['starttime']) && isset($data['endtime'])) {
            if (!empty($data['starttime']) && !empty($data['endtime'])) {
                $where['date'] = array(array('egt',strtotime($data['starttime'])),array('elt',strtotime($data['endtime'])));
            }
        }

        $loginLogList = db('crm_manage_login')->where($where)->limit(($data['page']-1)*$data['rows'],$data['rows'])->order('date DESC')->select();
        $count = db('crm_manage_login')->where($where)->count();

        $datas = array(
            'loginLogList'=>$loginLogList,
            'count'=>$count
        );
        apiReturn(200,'获取登录日志成功',$datas);
    }

    // 导入资料
    public function importCustomer()
    {
        $data = input();//token url文件路径

        if (empty($data['url'])) {
            apiReturn(201,'文件不存在');
        }

        $data_array = excels::readExcelFile($data['url']);
        if (empty($data_array)) {
            apiReturn(204,'文件内容为空或读取失败');
        }
        $phones = [];
        foreach ($data_array as $key => $value) {

            if ($key >= 1) {
                if (!empty($value[0]) && !empty($value[2])) {
                    $exist = db('crm_customer')->where('phone',$value[2])->find();
                    if ($exist) {
                        $phones[] = $value[2];
                    }else{
                        $max_client_id = db('crm_customer')->max('client_id');
                        $max_client_id = $max_client_id+1;
                        $source_type = 0;
                        if (isset($value[19])) {
                            $source_type = $value[19];
                        }
                        $province= $city = $area= '';

                        if(!empty($value[7])){
                           $title =  explode(' ',$value[7]);
                           if(count($title)>3){
                               $province_name = mb_substr(trim($title[0]), 0, 2);
                               $province = $this->crm_region($province_name);
                               $city_name = mb_substr(trim($title[1]), 0, 2);
                               $city = $this->crm_region($city_name);
                               $area_name = mb_substr(trim($title[2]), 0, 2);
                               $area = $this->crm_region($area_name);
                           }
                        }
                        $datas = array(
                            'client_id'=>$max_client_id,
                            'manage_id'=>99999,
                            'name'=>$value[0],
                            'sex'=>$value[1],
                            'phone'=>$value[2],
                            'phone2'=>$value[3],
                            'phone3'=>$value[4],
                            'weixin'=>$value[5],
                            'province'=>$province,
                            'city'=>$city,
                            'area'=>$area,
                            'address'=>$value[7],
                            'source'=>$value[10],
                            'date'=>strtotime(trim($value[12])),
                            'service_weixin'=>$value[13],
                            'remark'=>$value[16],
                            'grade'=>$value[18],
                            'source_type'=>$source_type
                        );
                        if ($source_type == 0) {
                            $source_id = db('crm_media')->where('media',$value[10])->value('id');
                            $source_type = db('crm_media_next')->where('media_id',$source_id)->value('type');
                            if (!empty($source_type)) {
                                $datas['source_type'] = $source_type;
                            }
                        }

                        db('crm_customer')->insert($datas);
                    }
                }
            }
        }
        $phones = implode(',', $phones);
        apiReturn(200,'导入成功',$phones);
    }

    public function crm_region($title){
        if($title){
            $region_id =  db('crm_region')->where('region_name','like',"%$title%")->value('region_id');
            if($region_id){
                return $region_id;
            }
        }
        return '';
    }

    // 导入用户
    public function importManage()
    {
        // $data = input();//token url文件路径

        // $data['url'] = 'https://xuexiang.oss-cn-hangzhou.aliyuncs.com/1683190163.xlsx';

        // $data_array = excels::readExcelFile($data['url']);
        // if (empty($data_array)) {
        //     apiReturn(204,'文件内容为空或读取失败');
        // }
        // foreach ($data_array as $key => $value) {
        //     if ($key >= 1) {
        //         if (!empty($value[0]) && !empty($value[1])) {
        //             //修改工号时修改客户归属和订单归属
        //             db('crm_order')->where(array('manage_id'=>$value[0]))->update(['manage_id'=>$value[1]]);
        //             db('crm_order_money')->where(array('manage_id'=>$value[0]))->update(['manage_id'=>$value[1]]);
        //         }
        //     }
        // }
        // apiReturn(200,'导入成功');
    }

    // 新增通话数量
    public function phoneNumberAdd()
    {
        $data = input();//token number
        if (empty($data['number'])) {
            apiReturn(201,'数量不能为空');
        }
        $manage_author = $this->getManageAuthor();
        $starttime = date('Y-m-d 00:00:00',time());
        $endtime = date('Y-m-d 23:59:59',time());
        $where['date'] = array(array('egt',strtotime($starttime)),array('elt',strtotime($endtime)));
        $where['manage_id'] = $manage_author['username'];
        $exist = db('crm_phone_number')->where($where)->find();
        if (empty($exist)) {
            $manageInfo = db('crm_manage')->where('username',$manage_author['username'])->find();
            $datas = array(
                'manage_id'=>$manageInfo['username'],
                'manage_name'=>$manageInfo['name'],
                'manage_type'=>$manageInfo['type'],
                'number'=>$data['number'],
                'date'=>time()
            );
            db('crm_phone_number')->insert($datas);
            apiReturn(200,'新增成功');
        }else{
            apiReturn(201,'今天数据已存在，请勿重复提交');
        } 
    }

    // 通话数量列表
    public function phoneNumberList()
    {
        $data = input();//token zu_id manage_id starttime endtime rows page

        $where = [];
        $manage_author = $this->getManageAuthor();
        if ($manage_author['is_xiaoshou'] == 1) {
            $where['manage_id'] = $this->getManageList();
        }
        if (isset($data['zu_id'])) {
            if (!empty($data['zu_id'])) {
                $wherezu_id = $this->getFenzuList($data['zu_id']);
                $where['manage_id'] = $this->getManageList($wherezu_id);
            }
        }
        if (isset($data['manage_id'])) {
            if (!empty($data['manage_id'])) {
                $where['manage_id'] = array('like','%'.$data['manage_id'].'%');
            }
        }
        if (isset($data['starttime']) && isset($data['endtime'])) {
            if (!empty($data['starttime']) && !empty($data['endtime'])) {
                $where['date'] = array(array('egt',strtotime($data['starttime'])),array('elt',strtotime($data['endtime'])));
            }
        }

        $list = db('crm_phone_number')->where($where)->limit(($data['page']-1)*$data['rows'],$data['rows'])->order('date DESC')->select();
        $count = db('crm_phone_number')->where($where)->count();

        apiReturn(200,'获取成功',['list'=>$list,'count'=>$count]);
    }

    // 删除通话记录
    public function phoneNumberDelete()
    {
        $data = input();//token id
        if (empty($data['id'])) {
            apiReturn(201,'id不能为空');
        }
        db('crm_phone_number')->where('id',$data['id'])->delete();
        apiReturn(200,'删除成功');
    }

    // 一键继承
    public function inherit()
    {
        $data = input();//manage_id inherit_manage_id
        if (!isset($data['manage_id']) || !isset($data['inherit_manage_id'])) {
            apiReturn(201,'参数错误');
        }
        if ($data['manage_id'] == $data['inherit_manage_id']) {
            apiReturn(201,'继承人和被继承人不可相同');
        }
        $manageInfo = db('crm_manage')->field('type')->where('username',$data['manage_id'])->find();
        $inheritManageInfo = db('crm_fenzu')->alias('a')->join('tp_crm_manage b','a.id=b.zu_id')->field('a.id as fenzu_id,a.name as fenzu_name,b.id as manage_id,b.name as manage_name,b.type as manage_type')->where('b.username',$data['inherit_manage_id'])->find();
        if ($manageInfo['type'] != $inheritManageInfo['manage_type']) {
            apiReturn(201,'继承人和被继承人必须为同一类型');
        }
        Db::startTrans();
        try{
            //继承订单
            $inheritOrder = db('crm_order')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id'],'zu_id'=>$inheritManageInfo['fenzu_id'],'zu_name'=>$inheritManageInfo['fenzu_name']]);
            $inheritOrderMoney = db('crm_order_money')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id'],'zu_id'=>$inheritManageInfo['fenzu_id'],'fenzu_name'=>$inheritManageInfo['fenzu_name']]);
            //继承微信号
            $inheritWeixin = db('crm_weixin')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id']]);
            //继承客户
            if ($inheritManageInfo['manage_type'] == 1) {//邀约
                $inheritCustomer = db('crm_customer')->where(['yaoyue_manage_id'=>$data['manage_id']])->update(['yaoyue_manage_id'=>$data['inherit_manage_id']]);
            }elseif ($inheritManageInfo['manage_type'] == 2) {//教务
                $inheritCustomer = db('crm_customer')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id'],'jiaowu_manage_id'=>$data['inherit_manage_id']]);
            }elseif ($inheritManageInfo['manage_type'] == 3) {//班主任
                $inheritCustomer = db('crm_customer')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id'],'banzhuren_manage_id'=>$data['inherit_manage_id']]);
            }else{
                Db::rollback();
                apiReturn(201,'非销售工号不可继承');
            }
            //继承客户工号关系表
            $inheritCustomerManage = db('crm_customer_manage')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id']]);
            //继承短信记录
            $inheritCustomerSms = db('crm_sms_record')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id']]);
            //继承客户跟进
            $inheritCustomerFollow = db('crm_customer_follow')->where(['follow_manage_id'=>$data['manage_id']])->update(['follow_manage_id'=>$data['inherit_manage_id'],'follow_manage_name'=>$inheritManageInfo['manage_name']]);
            //继承拨打电话设置
            $inheritCall = db('crm_call')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id']]);
            $inheritManageCall = db('crm_manage_call')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id']]);
            //继承登录日志
            $inheritLogin = db('crm_manage_login')->where(['username'=>$data['manage_id']])->update(['manage_id'=>$inheritManageInfo['manage_id'],'username'=>$data['inherit_manage_id'],'manage_name'=>$inheritManageInfo['manage_name']]);
            //继承大屏数据
            $inheritYingqiCount = db('crm_yingqi_count')->where(['manage_id'=>$data['manage_id']])->update(['manage_id'=>$data['inherit_manage_id']]);
            if ($inheritOrder || $inheritOrderMoney || $inheritWeixin || $inheritCustomer || $inheritCustomerSms || $inheritCustomerFollow || $inheritCustomerManage || $inheritCall || $inheritManageCall || $inheritYingqiCount) {
                Db::commit();
                apiReturn(200,'提交成功');
            }else{
                Db::rollback();
                apiReturn(201,'操作失败，请重新提交');
            }
        }catch (\Exception $e){
            Db::rollback();
            apiReturn(400,$e->getMessage());
        }
    }

}
